from django.conf import settings
from django.views.decorators.csrf import csrf_exempt

from apps.user.decorators import api_auth_required
from apps.user.models import User
from apps.user.service import get_user_info
from apps.news.models import News
from deps.voidsdk.django.modelautocode.tools import paginate_queryset
from deps.voidsdk.django.validator import (validate_params, not_blank,
        bool_validator, normal_date, phone_number)
from deps.voidsdk.django.responses import api_success_response, api_error_response

from .models import RecBanner


@csrf_exempt
@api_auth_required
@validate_params("GET", [
    {"name": "last_id", "clean_func": int, "required": False},
])
def recommend_users(request, cleaned_params):
    complete_set = User.objects.filter(is_supporter=False).exclude(sex=request.user.sex).order_by("-id")
    start_index = 0
    if cleaned_params["last_id"]:
        for index, u in enumerate(complete_set):
            if u.id == cleaned_params["last_id"]:
                start_index = index
    page_set = complete_set[start_index + 1: start_index + 21]
    users = [get_user_info(u) for u in page_set]
    return api_success_response({"users": users})


@csrf_exempt
@api_auth_required
@validate_params("GET", [
    {"name": "t", "clean_func": int, "required": True},
])
def recommend_banners(request, cleaned_params):
    banners = []
    for b in RecBanner.objects.filter(t=cleaned_params["t"]).order_by("order"):
        banner = {"pic": b.pic, "link": b.link}
        banners.append(banner)
    return api_success_response({"banners": banners})


@csrf_exempt
@api_auth_required
@validate_params("GET", [
    {"name": "last_id", "clean_func": int, "required": True},
])
def recommend_videos(request, cleaned_params):
    videos = []
    for n in News.objects.all().order_by("-id"):
        if n.video:
            vs = eval(n.video.strip())
            for v in vs:
                info = {
                        "news_id": n.id,
                        "video_src": v,
                        "owner": get_user_info(n.user),
                        "up_cnt": n.up_cnt
                }
                videos.append(info)

    complete_set = videos
    start_index = 0
    if cleaned_params["last_id"]:
        for index, n in enumerate(complete_set):
            if u.id == cleaned_params["last_id"]:
                start_index = index

    page_videos, pagination_data = paginate_queryset(videos, cleaned_params["page_no"])
    return api_success_response({"videos": page_videos, "pagination_data": pagination_data})
